import router from '@/router/index'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })
import useUserStore from './store/modules/user'
import setting from './setting'

//1. 任意路由切换实现进度条业务
/* 2.路由鉴权:控制路由组件的访问权限
 * 路由:登录 | 首页 | 404 | 任意 | 数据大屏 | 权限管理 | 商品管理
 * 未登录:只能访问登录;已登录:可访问除登录外所有路由
 */
router.beforeEach(async (to, from, next) => {
  document.title = setting.company + '-' + to.meta.title
  nprogress.start()
  let userStore = useUserStore()
  let token = userStore.token
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (userStore.userName) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next({ ...to }) //确保异步路由加载完毕后放行
        } catch (error) {
          //Token过期或token被手动修改时执行
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

router.afterEach((to, from) => {
  nprogress.done()
})
